#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * See http://www.cchensoft.com/opensource/cc-portal/license.txt
 * 
 * Author: Billy Zhang
 * Email: billy_zh@126.com
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Net;
using System.IO;
using System.Web.UI.WebControls;

using CchenSoft.Framework.Attributes;

using CchenSoft.Portal.Service;
using CchenSoft.Portal.Attributes;

namespace CchenSoft.Portal.Web.Controls
{
    [ParseChildren(true)]
    public class Portlets : ThemeControl
    {
        public Portlets()
        {
            SkinFileName = "portlets.ascx";
        }

        protected override void InitializeSkin(Control control)
        {
            Repeater r = (Repeater)control.FindControl("r");
            r.DataSource = GetPortletGroups(portalService.Portlets);
            r.ItemDataBound += new RepeaterItemEventHandler(r_ItemDataBound);
            r.DataBind();
        }

        private Dictionary<string, List<Portlet>> GetPortletGroups(ICollection<Portlet> portlets)
        {
            Dictionary<string, List<Portlet>> groups = new Dictionary<string, List<Portlet>>();
            foreach (Portlet p in portlets)
            {
                if (!groups.ContainsKey(p.Group))
                    groups.Add(p.Group, new List<Portlet>());

                groups[p.Group].Add(p);
            }

            return groups;
        }

        void r_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                KeyValuePair<string, List<Portlet>> kv = (KeyValuePair<string, List<Portlet>>)e.Item.DataItem;

                Literal ltGroup = (Literal)e.Item.FindControl("ltGroup");
                ltGroup.Text = kv.Key;

                Repeater r2 = (Repeater)e.Item.FindControl("r2");
                r2.ItemDataBound += new RepeaterItemEventHandler(r2_ItemDataBound);
                r2.DataSource = kv.Value;
                r2.DataBind();
            }
        }

        void r2_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Portlet p = (Portlet)e.Item.DataItem;

                Literal ltName = (Literal)e.Item.FindControl("ltName");
                ltName.Text = p.Description;

                HyperLink hlnkAdd = (HyperLink)e.Item.FindControl("hlnkAdd");
                hlnkAdd.NavigateUrl = string.Format("javascript:Portal.addPortlet(\"{0}\");", p.Name);
            }
        }
    }
}
